home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c++
- Subject: Re: [Q]Assigning function pointer in C/C++.
- Date: 19 Jan 1996 16:35:14 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan19113514@g7240065.bridge.bst.bls.com>
- References: <DL3JJu.5nB.0.queen@torfree.net> <4doc42$gsb@bmdhh222.bnr.ca>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: Ray Fallon's message of 19 Jan 1996 15:07:46 GMT
-
- In article <4doc42$gsb@bmdhh222.bnr.ca> Ray Fallon <ray.fallon@nt.com> writes:
-
- : bh332@freenet.toronto.on.ca (Karim Ladha) wrote:
- :>
- :>
- :> How is it possible to assign a declared variable in C++ a pointer to
- :> some function member? If you know of a solution, post. Greatly appreciated.
- :>
- :> In C for example;
- :> ...
- :> void( far *MyFunc )();
- :> ...
-
- : I response to your question, assigment of pointers to member functions is
- : not possible for the following reason :
-
- : In 'C' you can only have one instance of a function at any one time. In
- : C++ you can have multiple instances of a class (i.e. objects) and the
- : pointer to the function would not be able to know which object you are
- : referring to.
- <snip>
-
- Huh?
-
- You can have pointers to member functions providing you know what class (or base
- class) you are going to be assigning functions from.
-
- int (A::*p)(void);
-
- declares p as a pointer to an A member function which takes nothing and returns
- an int. The usage of p requires an object or pointer to an object of
- type A or derived from A. i.e:
-
- A a;
- int z = (a.*p)(); // Uses '.*' operator.
- or
- A* a = new B; // Where 'B' is derived from 'A'
- int z = (a->*p)(); // Uses '->*' operator.
-
- More complete example:
-
- #include <iostream.h>
-
- class A
- {
- public:
- virtual int func(void)
- { return 23; }
-
- int fred(void)
- { return 7; }
- };
-
- class B : public A
- {
- public:
- virtual int func(void)
- { return 71; }
-
- int fred(void)
- { return 24; }
- };
-
- int
- main(void)
- {
- int (A::*p)(void) = A::func;
- A a;
- A* b = new B;
-
- cout << (a.*p)() << endl; // Prints 23
- cout << (b->*p)() << endl; // Prints 71 (func is virtual)
-
- p = A::fred;
-
- cout << (a.*p)() << endl; // Prints 7
- cout << (b->*p)() << endl; // Prints 7 (fred is not virtual)
-
- return 0;
- }
-
- Hope this helps.
- Regards
-
- -A.
- --
- | A.Champion |
-